import request from '@/utils/request';
import {download, toFormData, checkDownloadRes} from '@/utils/common';
import fileImage from '@/assets/file.png';

/**
 * 分页查询文件信息管理
 */
export async function pageInfos(params) {
  const res = await request.get('/admin/cms/fileInfo/list', {params});
  if (res.data.code === 200) {
    for (let i = 0; i < res.data.rows.length; i++) {
      let fileInfo = res.data.rows[i];
      switch (fileInfo.fileSuffix) {
        case 'png':
        case 'jpg':
        case 'jpeg':
        case 'bmp':
        case 'gif':
          res.data.rows[i].pic = import.meta.env.VITE_API_URL + fileInfo.filePath;
          break;
        default:
          res.data.rows[i].pic = fileImage;
          break;
      }
    }
    console.log("res.data", res.data)
    return res.data;
  }
  return Promise.reject(new Error(res.data.msg));
}

/**
 * 添加文件信息管理
 */
export async function addInfo(data) {
  const res = await request.post('/admin/cms/fileInfo', data);
  if (res.data.code === 200) {
    return res.data.msg;
  }
  return Promise.reject(new Error(res.data.msg));
}

/**
 * 修改文件信息管理
 */
export async function updateInfo(data) {
  const res = await request.put('/admin/cms/fileInfo', data);
  if (res.data.code === 200) {
    return res.data.msg;
  }
  return Promise.reject(new Error(res.data.msg));
}

/**
 * 删除文件信息管理
 */
export async function removeInfo(id) {
  const res = await request.delete('/admin/cms/fileInfo/' + id);
  if (res.data.code === 200) {
    return res.data.msg;
  }
  return Promise.reject(new Error(res.data.msg));
}

/**
 * 批量删除文件信息管理
 */
export async function removeInfos(ids) {
  const res = await request.delete('/admin/cms/fileInfo/' + ids.join());
  if (res.data.code === 200) {
    return res.data.msg;
  }
  return Promise.reject(new Error(res.data.msg));
}

/**
 * 导出文件信息管理
 */
export async function exportInfos(params) {
  const res = await request({
    url: '/admin/cms/fileInfo/export',
    method: 'POST',
    data: toFormData(params),
    responseType: 'blob'
  });
  await checkDownloadRes(res);
  download(res.data, `info_${Date.now()}.xlsx`);
}
